var t = require("../../api.js"),
  a = getApp();

Page({
  data: {
    total_price: 0,
    cart_check_all: !1,
    cart_list: [],
    mch_list: [],
    loading: !0,
    check_all_self: !1,
    startX: 0,
    startY: 0,
    isTouchMove: false,
    edit_text:'编辑商品',
    edit_t:true
  },
  // 编辑商品
  modify_edit:function(){
    var that=this;
    if(that.data.edit_text=='编辑商品'){
      that.setData({
        edit_text: '完成',
        edit_t:false
      })
    }else{
      that.setData({
        edit_text: '编辑商品',
        edit_t: true
      })
    }
  },
  onLoad: function(t) {
    a.pageOnLoad(this, t);
    this.setData({
      shop_info: wx.getStorageSync('address_info')
    })
    this.themeColor()
  },
  themeColor: function () {
    var cl = wx.getStorageSync('_navigation_bar_color').themeColor;
    var cl_b = !cl || cl == '#ffffff' ? '#ff4544' : cl;
    var color_rgb = this.hexToRgb(cl_b);
    var back_g = 'rgba(' + color_rgb.r + ',' + color_rgb.g + ',' + color_rgb.b + ',.1)'
    this.setData({
      all_color: cl ? cl : '#ffffff',
      back_g: back_g
      // back_end: back_end
    });
  },
  hexToRgb: function (hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null;
  },
  onReady: function() {},
  onShow: function() {
    //wx.hideTabBar()
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        if (res.model.indexOf("X") >= 0 && res.model.indexOf('iPhone') >= 0) {
          that.setData({
            isIphoneX: true
          })
        }
      }
    })

    a.pageOnShow(this);
    var t = this;
    t.setData({
      cart_check_all: !1,
      show_cart_edit: !1,
      check_all_self: !1
    }), t.getCartList();
    this.show_navs();
    this.cart_num();
  },

  show_navs: function() {
    var that = this;
    var nav = wx.getStorageSync("_navbar");
    var url = "/pages/cart/cart";
    for (var i = 0; i < nav.navs.length; i++) {
      if (nav.navs[i].url == url) {
        if (getApp().globalData.nav_index == i) {
          if (typeof that.getTabBar === 'function' &&
            that.getTabBar()) {
            that.getTabBar().setData({
              selected: getApp().globalData.nav_index,
              is_show: 1
            })
          }
        } else {
          getApp().globalData.nav_index = i;
          if (typeof that.getTabBar === 'function' &&
            that.getTabBar()) {
            that.getTabBar().setData({
              selected: getApp().globalData.nav_index,
              is_show: 1
            })
          }
        }
      }
    }
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function(e) {
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
    })
  },
  touchmove: function(e) {

    var that = this,
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      index = e.currentTarget.dataset.index,
      cart_list = that.data.cart_list,
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    //滑动超过30度角 return
    if (Math.abs(angle) > 30) return;
    if (startX - touchMoveX > 80 && !cart_list[index].isTouchMove) {
      cart_list[index].isTouchMove = true;
      this.setData({
        cart_list: cart_list
      })
    }
    if (touchMoveX - startX > 80 && cart_list[index].isTouchMove) {
      //左滑
      cart_list[index].isTouchMove = false;
      this.setData({
        cart_list: cart_list
      })
    }
  },
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  getCartList: function() {
    var i = this;
    wx.showNavigationBarLoading(), i.setData({
      show_no_data_tip: !1
    }), a.request({
      url: t.cart.list,
      success: function(t) {
        if(0==t.code){
          for(var key in t.data.list){
            for (var k in i.data.cart_list) {
              if (t.data.list[key].cart_id == i.data.cart_list[k].cart_id && i.data.cart_list[k].checked){
                t.data.list[key].checked=1;
                i.data.is_one_show = 1;
              } else if (t.data.list[key].cart_id == i.data.cart_list[k].cart_id) {
                t.data.list[key].is_checked = 1;
                i.data.is_one_show = 1;
              }
              if (t.data.list[key].cart_id == i.data.cart_list[k].cart_id && i.data.cart_list[k].num != t.data.list[key].num) {
                t.data.list[key].num = i.data.cart_list[k].num
              }
            }
            if (!t.data.list[key].is_checked && !t.data.list[key].checked) {
              t.data.list[key].checked = 1;
            }
          }
        }
        0 == t.code && i.setData({
          cart_list: t.data.list,
          mch_list: t.data.mch_list,
          total_price: 0,
          cart_check_all: !1,
          show_cart_edit: !1
        }), i.setData({
          show_no_data_tip: 0 == i.data.cart_list.length
        });
      },
      complete: function() {
        wx.hideNavigationBarLoading(), i.setData({
          loading: !1
        });
        if (!i.data.is_one_show){
          i.cartCheckAll();
        }
        i.updateTotalPrice()
      }
    });
  },
  cartLess: function(t) {
    var a = this;
    if (t.currentTarget.dataset.type && "mch" == t.currentTarget.dataset.type) {
      var i = t.currentTarget.dataset.mchIndex,
        c = t.currentTarget.dataset.index;
      a.data.mch_list[i].list[c].num = a.data.mch_list[i].list[c].num - 1, a.data.mch_list[i].list[c].price = a.data.mch_list[i].list[c].num * a.data.mch_list[i].list[c].unitPrice,
        a.setData({
          mch_list: a.data.mch_list
        });
    } else {
      var e = a.data.cart_list;
      for (var s in e) t.currentTarget.id == e[s].cart_id && ((e[s].shop_count> 0 ? e[s].num > e[s].shop_count : e[s].num > 1) || a.delete_cart(t.currentTarget.id)) && (e[s].num = (e[s].shop_count > 0? a.data.cart_list[s].num - e[s].shop_count : a.data.cart_list[s].num - 1),
        e[s].price = a.data.cart_list[s].unitPrice * e[s].num, a.setData({
          cart_list: e
        }));
    }
    a.updateTotalPrice();
  },

  delete_cart: function(cart_id) {
    var a = this;
    wx.showModal({
      title: '提示',
      content: '是否确认删除',
      success: function(res) {
        if (res.confirm){
          var e = a.data.cart_list;
          for (var s in e) cart_id == e[s].cart_id && (a.showpicker_reduce(e[s].goods_id));
        }
      }

    })
    return false;
  },

  showpicker_reduce: function(tt) {
    var i = this;
    if (typeof(tt) == "number" || typeof(tt) == "string") {
      var goods_id = tt;
    } else {
      var goods_id = tt.currentTarget.dataset.id
    }
    a.request({
      url: t.default.cart_reduce,
      data: {
        goods_id: goods_id,
        is_delete: 1
      },
      success: function(t) {
        if (0 == t.code) {
          i.onShow();
        } else {
          wx.showToast({
            title: t.msg,
            icon: "none",
            duration: 1500
          })
        }
        i.cart_num();
      }
    })
  },


  cartAdd: function(t) {
    var a = this;
    if (t.currentTarget.dataset.type && "mch" == t.currentTarget.dataset.type) {
      var i = t.currentTarget.dataset.mchIndex,
        c = t.currentTarget.dataset.index;
      a.data.mch_list[i].list[c].num = a.data.mch_list[i].list[c].num + 1, a.data.mch_list[i].list[c].price = a.data.mch_list[i].list[c].num * a.data.mch_list[i].list[c].unitPrice,
        a.setData({
          mch_list: a.data.mch_list
        });
    } else {
      var e = a.data.cart_list;
      for (var s in e) t.currentTarget.id == e[s].cart_id && (e[s].shop_count> 0 ? e[s].num+=e[s].shop_count : e[s].num = a.data.cart_list[s].num + 1,
        e[s].price = a.data.cart_list[s].unitPrice * e[s].num, a.setData({
          cart_list: e
        }));
    }
    a.updateTotalPrice();
  },
  cartCheck: function(t) {
    var a = this,
      i = t.currentTarget.dataset.index,
      c = t.currentTarget.dataset.type,
      e = t.currentTarget.dataset.mchIndex;
    "self" == c && (a.data.cart_list[i].checked = !a.data.cart_list[i].checked, a.setData({
      cart_list: a.data.cart_list
    })), "mch" == c && (a.data.mch_list[e].list[i].checked = !a.data.mch_list[e].list[i].checked,
      a.setData({
        mch_list: a.data.mch_list
      })), a.updateTotalPrice();
  },
  cartCheckAll: function() {
    var t = this,
      a = t.data.cart_list,
      i = !1;
    i = !t.data.cart_check_all;
    for (var c in a) a[c].disabled && !t.data.show_cart_edit || (a[c].checked = i);
    if (t.data.mch_list && t.data.mch_list.length)
      for (var c in t.data.mch_list)
        for (var e in t.data.mch_list[c].list) t.data.mch_list[c].list[e].checked = i;
    t.setData({
      cart_check_all: i,
      cart_list: a,
      mch_list: t.data.mch_list
    }), t.updateTotalPrice();
  },
  updateTotalPrice: function() {
    var t = this,
      a = 0,
      i = t.data.cart_list;
    for (var c in i) i[c].checked && (a += i[c].price);
    for (var c in t.data.mch_list)
      for (var e in t.data.mch_list[c].list) t.data.mch_list[c].list[e].checked && (a += t.data.mch_list[c].list[e].price);
    t.setData({
      total_price: a.toFixed(2)
    });
  },
  cartSubmit: function() {
    var t = this,
      a = t.data.cart_list,
      i = t.data.mch_list,
      c = [],
      e = [],
      s = [],
      r = [];
    for (var l in a) a[l].checked && (c.push(a[l].cart_id), r.push({
      cart_id: a[l].cart_id
    }));
    c.length > 0 && s.push({
      mch_id: 0,
      goods_list: r
    });
    for (var l in i) {
      var d = [],
        n = [];
      if (i[l].list && i[l].list.length)
        for (var h in i[l].list) i[l].list[h].checked && (d.push(i[l].list[h].cart_id),
          n.push({
            cart_id: i[l].list[h].cart_id
          }));
      d.length && (e.push({
        id: i[l].id,
        cart_id_list: d
      }), s.push({
        mch_id: i[l].id,
        goods_list: n
      }));
    }
    if (0 == c.length && 0 == e.length) return !0;
    wx.showLoading({
      title: "正在提交",
      mask: !0
    }), t.saveCart(function() {
      wx.navigateTo({
        url: "/pages/new-order-submit/new-order-submit?mch_list=" + JSON.stringify(s)
      });
    }), wx.hideLoading();
  },
  cartEdit: function() {
    var t = this,
      a = t.data.cart_list;
    for (var i in a) a[i].checked = !1;
    t.setData({
      cart_list: a,
      show_cart_edit: !0,
      cart_check_all: !1
    }), t.updateTotalPrice();
  },
  cartDone: function() {
    var t = this,
      a = t.data.cart_list;
    for (var i in a) a[i].checked = !1;
    t.setData({
      cart_list: a,
      show_cart_edit: !1,
      cart_check_all: !1
    }), t.updateTotalPrice();
  },
  cartDelete: function() {
    var i = this,
      c = i.data.cart_list,
      e = [];
    for (var s in c) c[s].checked && e.push(c[s].cart_id);
    if (i.data.mch_list && i.data.mch_list.length)
      for (var s in i.data.mch_list)
        for (var r in i.data.mch_list[s].list) i.data.mch_list[s].list[r].checked && e.push(i.data.mch_list[s].list[r].cart_id);
    if (0 == e.length) return !0;
    wx.showModal({
      title: "提示",
      content: "确认删除" + e.length + "项内容？",
      success: function(c) {
        if (c.cancel) return !0;
        wx.showLoading({
          title: "正在删除",
          mask: !0
        }), a.request({
          url: t.cart.delete,
          data: {
            cart_id_list: JSON.stringify(e)
          },
          success: function(t) {
            wx.hideLoading(), wx.showToast({
              title: t.msg
            }), 0 == t.code && i.getCartList(), t.code;
          }
        });
      }
    });
  },
  onHide: function() {
    this.saveCart();
  },
  onUnload: function() {
    this.saveCart();
  },
  saveCart: function(i) {
    var c = this,
      e = JSON.stringify(c.data.cart_list);
    a.request({
      url: t.cart.cart_edit,
      method: "post",
      data: {
        list: e,
        mch_list: JSON.stringify(c.data.mch_list)
      },
      success: function(t) {
        t.code;
      },
      complete: function() {
        "function" == typeof i && i();
      }
    });
  },
  checkGroup: function(t) {
    var a = this,
      i = t.currentTarget.dataset.type,
      c = t.currentTarget.dataset.index;
    if ("self" == i) {
      for (var e in a.data.cart_list) a.data.cart_list[e].checked = !a.data.check_all_self;
      a.setData({
        check_all_self: !a.data.check_all_self,
        cart_list: a.data.cart_list
      });
    }
    if ("mch" == i) {
      for (var e in a.data.mch_list[c].list) a.data.mch_list[c].list[e].checked = !a.data.mch_list[c].checked_all;
      a.data.mch_list[c].checked_all = !a.data.mch_list[c].checked_all, a.setData({
        mch_list: a.data.mch_list
      });
    }
    a.updateTotalPrice();
  },
  switchTab(e) {
    const data = e.currentTarget.dataset
    const url = data.path
    wx.switchTab({
      url
    })
    // this.setData({
    //   selected: data.index
    // })
  },
  // 获取购物车数量
  cart_num: function () {
    var that = this;

    wx.getStorage({
      key: 'user_info',
      success: function (res) {
        a.request({
          url: t.cart.list,
          success: function (t) {
            if (0 == t.code) {
              if (typeof that.getTabBar === 'function' &&
                that.getTabBar()) {
                if (t.data.mch_list.length>0){
                    var length = t.data.list.length + t.data.mch_list[0].list.length;
                }else {
                    var length = t.data.list.length
                }
                that.getTabBar().setData({
                  cart_num: length
                })
              }
            }
          }
        });
      },
    })
  }
});